﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Db4objects.Db4o;

namespace ADB_QuanLyThuVien
{
    public class DAO_ReturnBook
    {
        internal static string CreateReturnForm(PhieuTra pt, Account acc, string idPhieuMuon, List<Book> lReturnBook)
        {
            string kq = "";
            pt.IdForm = GetNextId();
            pt.LBook = new List<Book>();
            pt.DateCreateForm = DateTime.Today;
            Member employee = DAO_Member.SelectMember(acc);
            var config = Db4oEmbedded.NewConfiguration();
            config.Common.ObjectClass(typeof(PhieuMuon)).CascadeOnUpdate(true);
            IObjectContainer db = Db4oEmbedded.OpenFile(config, QLTV_System.ConnectString);
            //Tro den doi tuong phiếu mượn
            PhieuMuon pm = new PhieuMuon();
            pm.IdForm = idPhieuMuon;
            IObjectSet rReader = db.QueryByExample(pm);
            pt.pm = (PhieuMuon)rReader.Next();
            //Trỏ đến đối tượng sách trả
            for (int i = 0; i<lReturnBook.Count;++i)
            {
                IObjectSet rBook = db.QueryByExample(lReturnBook[i]);
                Book sach = (Book)rBook.Next();
                sach.Soluong += 1;
                pt.LBook.Add(sach);
                db.Store(sach);
            }
            //Trỏ đến đối tượng nhân viên nhận sách trả
            IObjectSet rEmployee = db.QueryByExample(employee);
            pt.Employee = (Member)rEmployee.Next();
            db.Store(pt);
            db.Close();
            if (pm.ExpirationDate < pt.DateCreateForm)
                kq += "Trả sách thành công";
            else
                kq += "Sách bạn trả đã quá hạn";
            return kq;
        }

        private static string GetNextId()
        {
            string id = "PT";
            DateTime now = DateTime.Now;
            id += now.Year.ToString("0000") + now.Month.ToString("00") + now.Day.ToString("00") + now.Hour.ToString("00") + now.Minute.ToString("00") + now.Second.ToString("00");
            return id;
        }

        internal static List<PhieuTra> SelectAll()
        {
            List<PhieuTra> lPhieuTra = new List<PhieuTra>();
            IObjectContainer db = Db4oEmbedded.OpenFile(QLTV_System.ConnectString);
            IObjectSet result = db.QueryByExample(new PhieuTra());
            for (int i = 0; i < result.Count;++i )
                lPhieuTra.Add((PhieuTra)result[i]);
            db.Close();
            return lPhieuTra;
        }
    }
}
